import React, { useState, useEffect } from 'react';
import { renderToString } from 'react-dom/server';
import axios from 'axios';

// 样式美化可以使用第三方库，如 styled-components、Material-UI 等

// 首页组件
function HomePage() {
  const [news, setNews] = useState([]);

  useEffect(() => {
    fetchNews();
  }, []);

  async function fetchNews() {
    try {
      const response = await axios.get('https://api.hnpwa.com/v0/news/1.json');
      setNews(response.data);
    } catch (error) {
      console.error('Error fetching news:', error);
    }
  }

  return (
    <div>
      <h1>Hacker News</h1>
      <ul>
        {news.map((item: any) => (
          <li key={item.id}>
            <a href={item.url} target="_blank" rel="noopener noreferrer">
              {item.title}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

// 搜索页组件
function SearchPage() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  async function searchNews() {
    try {
      const response = await axios.get(
        `https://api.hnpwa.com/v0/search/${encodeURIComponent(query)}.json`
      );
      setResults(response.data);
    } catch (error) {
      console.error('Error searching news:', error);
    }
  }

  function handleInputChange(event: React.ChangeEvent<HTMLInputElement>) {
    setQuery(event.target.value);
  }

  function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    searchNews();
  }

  return (
    <div>
      <h1>Search News</h1>
      <form onSubmit={handleSubmit}>
        <input type="text" value={query} onChange={handleInputChange} />
        <button type="submit">Search</button>
      </form>
      <ul>
        {results.map((item: any) => (
          <li key={item.id}>
            <a href={item.url} target="_blank" rel="noopener noreferrer">
              {item.title}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

// App 组件，根据路由展示不同页面
function App() {
  const [currentPage, setCurrentPage] = useState('home');

  function handleNavClick(page: string) {
    setCurrentPage(page);
  }

  let content;
  if (currentPage === 'home') {
    content = <HomePage />;
  } else if (currentPage === 'search') {
    content = <SearchPage />;
  }

  return (
    <div>
      <nav>
        <button onClick={() => handleNavClick('home')}>Home</button>
        <button onClick={() => handleNavClick('search')}>Search</button>
      </nav>
      {content}
    </div>
  );
}

// 服务端渲染入口


export default App;
